package com.tubang.logistics.controller;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tubang.common.util.BeanMapper;
import com.tubang.common.util.GsonQuick;
import com.tubang.common.util.MsgCode;
import com.tubang.common.util.ResultData;
import com.tubang.common.util.StringUtils;
import com.tubang.component.entity.UserEntity;
import com.tubang.component.service.IUserService;
import com.tubang.component.util.RequestUtil;
import com.tubang.component.vo.UserVo;
import com.tubang.logistics.entity.TruckEntity;
import com.tubang.logistics.service.ITruckService;
import com.tubang.logistics.vo.TruckDetailVo;
import com.tubang.logistics.vo.TruckVo;

/**
 * <p>
 * 车辆表 前端控制器
 * </p>
 *
 * @author wsl
 * @since 2017-12-13
 */
@RestController
@RequestMapping("/truck")
public class TruckController {
	
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    private ITruckService truckService;
    @Resource
    private IUserService userService;
    
    /**
     * @Title appInsertOrUpdate 
     * @Description 新增车辆 或者 修改车辆信息
     * @param  truckVo
     * @param  userVo
     * @return ResultData 返回类型 
     * @throws
     */
    @PostMapping(value = "appInsertOrUpdate")
    public ResultData appInsertOrUpdate(HttpServletRequest request, HttpServletResponse response) {
    	String receivePostJson = RequestUtil.receivePostJson(request);
    	TruckVo truckVo = GsonQuick.toObject(receivePostJson, TruckVo.class);
    	String userId = GsonQuick.getString(receivePostJson, "userId");
    	String truckId = GsonQuick.getString(receivePostJson, "truckId");
		try {
			//保存车辆信息
			TruckEntity truckEntity = BeanMapper.map(truckVo, TruckEntity.class);
			truckEntity.setUpdateTime(new Date());
			if (StringUtils.isNotBlank(truckId)) {//车辆更新
				truckEntity.setId(truckId);
				truckService.updateById(truckEntity);
				return ResultData.result(true);
			}else {//车辆新增
				UserEntity userEntity = userService.selectById(userId);
				if(StringUtils.isBlank(userId)||null ==userEntity){
					return ResultData.result(false).setCode(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST).setMsg(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST_DESC);
				}
				truckEntity.setUserId(userId);
				truckService.insert(truckEntity);
				logger.info("[truck]<== method[appInsertOrUpdate],插入卡车数据为 ：[{}] ", GsonQuick.getGson().toJson(truckEntity));
				return ResultData.result(true).setData(truckEntity);
			}
		} catch (Exception e) {
			logger.error("[truck]<== method[appInsertOrUpdate], 车辆查询失败 addressId:[{}]", e.getMessage());
			e.printStackTrace();
			return ResultData.result(false).setData(e);
		}
       
    }

    /**
     * @Description 根据用户查询车辆列表 包括条件查询
     * @param truckVo
     * @return
     */
	@GetMapping(value = "selectByCompanyId")
	public ResultData selectByCompanyId(TruckVo truckVo) {
    	
        logger.info("[truck]==> method[selectByUserId],请求userId：{}", GsonQuick.getGson().toJson(truckVo));
		try {
			TruckEntity truckEntity = BeanMapper.map(truckVo, TruckEntity.class);
			EntityWrapper<TruckEntity> wrapper = new EntityWrapper<>(truckEntity);
			
			Page<TruckEntity> page = truckService.selectPage(new Page<>(truckVo.getPage(),truckVo.getRows()),wrapper);
			int totalCount = truckService.selectCount(wrapper);
			
			logger.info("[truck]<== method[selectByUserId], 查询结果：{}", GsonQuick.getGson().toJson(page));
			return ResultData.result(true).setData(page.getRecords()).setTotalCount(totalCount);
		} catch (Exception e) {
			logger.error("[truck]<== method[selectByUserId], 查询失败：{}", e.getMessage());
			e.printStackTrace();
			return ResultData.result(false).setData(e);
		}
    }
    
    /**
     * @Title insertOrUpdate 
     * @Description 新增车辆 或者 修改车辆信息
     * @param  truckVo
     * @param  userVo
     * @return ResultData 返回类型 
     * @throws
     */
    @PostMapping(value = "insertOrUpdate")
    public ResultData insertOrUpdate(HttpServletRequest request, HttpServletResponse response) {
    	String receivePostJson = RequestUtil.receivePostJson(request);
    	UserVo userVo = GsonQuick.toObject(receivePostJson, UserVo.class);
    	TruckVo truckVo = GsonQuick.toObject(receivePostJson, TruckVo.class);
    	String userId = GsonQuick.getString(receivePostJson, "userId");
    	String truckId = GsonQuick.getString(receivePostJson, "truckId");
    	if (StringUtils.isNotBlank(truckId)) {
    		truckVo.setId(truckId);
		}
    	if (StringUtils.isNotBlank(userId)) {
    		userVo.setId(userId);
    	}
		try {
			//保存车主信息
			UserEntity userEntity = BeanMapper.map(userVo, UserEntity.class);
			userEntity.setUpdateTime(new Date());
			userService.insertOrUpdate(userEntity);
			logger.info("[truck]<== method[insertOrUpdate],插入车主数据为 ：[{}] ", GsonQuick.getGson().toJson(userEntity));
			//保存卡车信息
			TruckEntity truckEntity = BeanMapper.map(truckVo, TruckEntity.class);
			truckEntity.setUserId(userEntity.getId());
			truckEntity.setUpdateTime(new Date());
			truckService.insertOrUpdate(truckEntity);
			logger.info("[truck]<== method[insertOrUpdate],插入卡车数据为 ：[{}] ", GsonQuick.getGson().toJson(truckEntity));
			return ResultData.result(true);
		} catch (Exception e) {
			logger.error("[truck]<== method[insertOrUpdate], 车辆查询失败 addressId:[{}]", e.getMessage());
			e.printStackTrace();
			return ResultData.result(false).setData(e);
		}
       
    }
    
    /**
     * @Description 根据id查询车辆信息
     * @param String id 车辆唯一编号
     * @Title selectById
     * @return ResultData
     */
    @GetMapping(value = "selectById")
    public ResultData selectById(@RequestParam(required = true) String id) {
    	
    	logger.info("[truck]==> method[selectById],请求truckId：{}", id);
        try {
			TruckEntity truckEntity = truckService.selectById(id);
			if (null != truckEntity) {
				UserEntity userEntity = userService.selectById(truckEntity.getUserId());
				TruckDetailVo truckDetailVo= new TruckDetailVo();
				truckDetailVo.setTruckEntity(truckEntity);
				truckDetailVo.setUserEntity(userEntity);
			    logger.info("[truck]<== method[selectById], 车辆查询结果为{}", GsonQuick.getGson().toJson(truckDetailVo));
			    return ResultData.result(true).setData(truckDetailVo);
			} else {
			    logger.info("[truck]<== method[selectById], 车辆查询失败 addressId:[{}]", id);
			    return ResultData.result(true).setCode(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST).setMsg(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST_DESC);
			}
		} catch (Exception e) {
			logger.error("[truck]<== method[selectById], 车辆查询失败 addressId:[{}]",e.getMessage());
			e.printStackTrace();
			return ResultData.result(false).setData(e);
		}
    }
    
    /**
     * @Description 车辆认证
     * @param String id 车辆编号
     * @Title setDefaultAddress
     * @return ResultData
     */
	@PutMapping(value = "truckCertification")
    public ResultData check(HttpServletRequest request, HttpServletResponse response) {
    	String receivePostJson = RequestUtil.receivePostJson(request);
    	TruckEntity truckEntity = GsonQuick.toObject(receivePostJson,TruckEntity.class);
    	logger.info("[truck]==> method[selectById],请求truckId：{}", GsonQuick.getGson().toJson(truckEntity));
        try {
        	if (null != truckEntity) {
        		truckEntity.setUpdateTime(new Date());
        		truckService.updateById(truckEntity);
        		logger.info("[truck]<== method[selectById], 车辆认证结果为{}", GsonQuick.getGson().toJson(truckEntity));
			    return ResultData.result(true).setData(truckEntity);		
        	}else {
        		logger.info("[truck]<== method[selectById], 车辆认证失败 :[{}]");
			    return ResultData.result(true).setCode(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST).setMsg(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST_DESC);
			}
        } catch (Exception e) {
        	e.printStackTrace();
        	logger.error("[truck]<== method[selectById], 车辆认证失败 :[{}]",e.getMessage());
        	return ResultData.result(false).setData(e);
		}
    }
	
	
	/**
	 * @Description app-车辆认证
	 * @param String id 车辆编号
	 * @Title setDefaultAddress
	 * @return ResultData
	 */
    @PostMapping(value = "appTruckCertification")
    public ResultData appTruckCertification(HttpServletRequest request, HttpServletResponse response) {
    	String receivePostJson = RequestUtil.receivePostJson(request);
    	TruckVo truckVo = GsonQuick.toObject(receivePostJson, TruckVo.class);
    	String userId = GsonQuick.getString(receivePostJson, "userId");
		try {
			//保存车辆信息
			TruckEntity truckEntity = BeanMapper.map(truckVo, TruckEntity.class);
			truckEntity.setUpdateTime(new Date());
			UserEntity userEntity = userService.selectById(userId);
			if(StringUtils.isBlank(userId)||null ==userEntity){
				return ResultData.result(false).setCode(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST).setMsg(MsgCode.ADDRESS_FAIL_IS_NOT_EXIST_DESC);
			}
			truckEntity.setUserId(userId);
			truckService.insertOrUpdate(truckEntity);
			logger.info("[truck]<== method[appInsertOrUpdate],插入卡车数据为 ：[{}] ", GsonQuick.getGson().toJson(truckEntity));
			return ResultData.result(true).setData(truckEntity);
		} catch (Exception e) {
			logger.error("[truck]<== method[appInsertOrUpdate], 车辆查询失败 addressId:[{}]", e.getMessage());
			e.printStackTrace();
			return ResultData.result(false).setData(e);
		}
       
    }
	
}
